package fusion

import (
	"database/sql"
	"fmt"
	"log"
)

type IGetTableName interface {
	GetTableName() string
}

func RunDBTransaction(db *sql.DB, f func(tx *sql.Tx) error) error {
	tx, err := db.Begin()
	if err != nil {
		return err
	}
	if err = f(tx); err != nil {
		if err := tx.Rollback(); err != nil {
			log.Printf("rollback transaction failed, %s.\n", err)
		}
		return err
	}
	if err = tx.Commit(); err != nil {
		return err
	}
	return nil
}

func RunDBBatchDelete(tx *sql.Tx,
	tblNames []string, keyName string, keyValue interface{}) error {
	for _, tblName := range tblNames {
		_, err := tx.Exec(fmt.Sprintf(
			"DELETE FROM `%s` WHERE `%s`=?", tblName, keyName), keyValue)
		if err != nil {
			return err
		}
	}
	return nil
}
